import { Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

import { Repository, Like } from 'typeorm';
// import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Tags } from './entities/tags.entity';
import { UserRepository } from './user.repository';

/* 
1.引入 InjectRepository typeOrm 依赖注入 接受一个实体

2.引入类型 Repository 接受实体泛型

3.Like 用于模糊查询

4.save 保存  find 查询 update 更新 delete 删除
*/
@Injectable()
export class UserService {

  private readonly user: Repository<User>
  private readonly tag: Repository<Tags>

  constructor(@Inject() useRepository: UserRepository) {
    const repository = useRepository.getRepository()
    this.user = repository.user
    this.tag = repository.tag
  }

  //通过前端传入的userId 查到当前id 的用户信息，然后拿到前端传入的tags [tag1,tag2,tag3]
  // 进行遍历 给tag实例进行赋值 然后调用保存方法添加tag 添加完之后 通过 tagList 保存该tag类
  // 最后把tagList 赋给 user类的tags属性 然后重新调用save 进行更新
  async addTags(params: { tags: string[], userId: number }) {
    const userInfo = await this.user.findOne({ where: { id: params.userId } })
    if (!userInfo) {
      throw new Error('user不存在')
    }

    const tagList: Tags[] = []
    for (let i = 0; i < params.tags.length; i++) {
      let T = new Tags()
      T.tags = params.tags[i]
      await this.tag.save(T)
      tagList.push(T)
    }
    userInfo.tags = tagList
    return this.user.save(userInfo)
  }

  create(createUserDto: CreateUserDto) {
    const data = new User()
    data.name = createUserDto.name
    data.desc = createUserDto.desc
    return this.user.save(data);
  }

  async findAll(query: { keyWord?: string, page: number, pageSize: number, limit?: number }) {
    const data = await this.user.find({
      //查询的时候如果需要联合查询需要增加 relations
      relations: ['tags'],
      where: {
        name: Like(`%${query.keyWord}%`)
      },
      order: {
        id: 'DESC'
      },
      skip: (query.page - 1) * query.pageSize,
      take: query.pageSize
    })
    const total = await this.user.count({
      where: {
        name: Like(`%${query.keyWord}%`)
      }
    })
    return {
      data,
      total
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: any, updateUserDto: UpdateUserDto) {
    return this.user.update(id, updateUserDto);
  }

  remove(id: number) {
    return this.user.delete(id);
  }

  delete(id: number) {
    return this.user.delete(id);
  }
}
